function toggleFullScreen(selectedItem) {
    if($('#top').is(':visible')) {
        $('#top').hide();
        $('#fullscreen-text').html('Quitter le plein ecran');
        $(window).trigger("resize");
    } else {
        $('#top').show();
        $('#fullscreen-text').html('Plein ecran');
        $(window).trigger("resize");
    }
}

function open_purge(selectedItem) {
    message = "Vous êtes sur le point de supprimer les rendez-vous de ces 3 derniers mois<br/><font color='red'><strong>Attention, cette action est irréversible</strong></font>";
    alert_jqueryui_ok(message, function() {
        post_array = {
            magic : 'purge_data'
        };
        ajax(WEBROOT+"/getdata/purge_data", post_array, function(data) {
            if(getRest(data)['code'] == 200) {
                notification_jqueryui(getRest(data)['message']);
            } else {
                notification_jqueryui(getRest(data)['message']);
            }
        });  
    });
}

function ajax_save_agendas(selectedItem) {
    ajax_config_element($('#afficher_agendas'));
    
}

function ajax_save_google(selectedItem) {
    $login_google = $('#login_google');
    $pwd_google = $('#pwd_google');
    $agenda_google = $('#agenda_google');
    $google_agenda_id = $('#google_agenda_id');
    post_array = {
        'login':$login_google.val(), 
        'password':$pwd_google.val(), 
        'agenda_google':$agenda_google.val(), 
        'google_agenda_id':$google_agenda_id.val()
    }
    
    ajax(WEBROOT+"/getdata/google_synchronize", post_array, function(data) {
        if(getRest(data)['code'] == 200) {
            $('#header_afficher_sync_popup').dialog('close');
            notification_jqueryui(getRest(data)['message']);
        } else {
            notification_jqueryui(getRest(data)['message']);
        }
    });  
}


function ajax_config_element(selectedItem) {
    var column_name = selectedItem.attr('name'); // Avoid redudancy
    var data_type = selectedItem.attr('type');
    var data_genre = (selectedItem.attr('data-genre') != undefined) ? selectedItem.attr('data-genre') : 'calendar_element';
    var value = selectedItem.val();
    // Check integrity of new values
    ///////////////////////////////////
    // If selected hours can't match'
    if(selectedItem.hasClass('calendar-config-hour')) {
        if($('#heure_de_debut').length && $('#heure_de_fin').length) {
            if(parseInt($('#heure_de_debut').val(), 10) > parseInt($('#heure_de_fin').val(), 10)) {
                selectedItem.val(selectedItem.data('prev'));
                displayError("L'heure de début doit précéder l'heure de fin");
                return false;
            }
        }
    }


    // Browse
    if(selectedItem.attr('id') == 'calendar-previous-btn') {
        $('#calendar').weekCalendar("prev");
        load_help();
    }
    if(selectedItem.attr('id') == 'calendar-next-btn') {
        $('#calendar').weekCalendar("next");
        load_help();
    }
    if(selectedItem.attr('id') == 'calendar-today-btn') {
        $('#calendar').weekCalendar("today");
        $('#date_de_depart').val('');
        load_help();
    }
    
    
    // Agenda types
    // 
    // 
    // CALENDAR OPTIONS
    // If a specific date was selected
    if(selectedItem.attr('id') == 'afficher_agendas') {
        var selectedNodes = $('.dynatree-container[data-content="afficher_agendas"]').dynatree("getSelectedNodes");
        if(selectedNodes.length) {
            var users = new Array();
            var usersId = new Array();
            var selectedKeys = $.map(selectedNodes, function(node){
                if(!isNaN(node.data.key)) { 
                    users.push(node.data.title);
                    usersId.push(node.data.key);
                }
                return  node.data.title;
            });

            window.agendaArray = users;
            window.agendaIdArray = usersId;
            
            $('#calendar').weekCalendar("option", "users", users); 
            $('#header_afficher_agendas_popup').dialog('close');
            $(window).resize(); 
            $('#calendar').weekCalendar('refresh');
        }
    } else if(selectedItem.hasClass('calendar-config-date')) {
        var dateArray = selectedItem.val().split('/');
        // Javascript Date(Y, M, D) with month starting at 0
        var calendarDate = new Date(dateArray[2], dateArray[1]-1, dateArray[0]);
        $('#calendar').weekCalendar("gotoDate", calendarDate);
        $('#calendar').weekCalendar('refresh');
        //$('#header_options_affichage_popup').dialog('close');
        return false;
    } else if(selectedItem.attr('name') == 'jours_a_afficher') {
        $('#calendar').weekCalendar("option", "daysToShow", parseInt(selectedItem.val(), 10)); 
        $(window).resize(); 
        $('#calendar').weekCalendar('refresh');
    //$('#header_options_affichage_popup').dialog('close');
    } else if(selectedItem.attr('id') == 'nb_intervalles_par_heure') {
        $('#calendar').weekCalendar("option", "timeslotsPerHour", selectedItem.val()); 
        $(window).resize(); 
        $('#calendar').weekCalendar('refresh');
    //$('#header_options_affichage_popup').dialog('close');
    } else if(selectedItem.attr('id') == 'heure_de_debut' || selectedItem.attr('id') == 'heure_de_fin') {
        $('#calendar').weekCalendar("option", "businessHours", {
            'start':parseInt($('#heure_de_debut').val(), 10),
            'end':parseInt($('#heure_de_fin').val(), 10),
            'limitDisplay': true
        }); 
        $(window).resize(); 
        $('#calendar').weekCalendar('refresh');
    //$('#header_options_affichage_popup').dialog('close');
    } else if(selectedItem.attr('id') == 'jour_de_demarrage') {
        var first_day = $('td.wc-day-1').find('.wc-day-column-notes').attr('data-date-time');
        date =  new Date(first_day*1000);
        if(selectedItem.val() != "today") {
            var associativeDays = {
                'monday':1, 
                'tuesday':2, 
                'wednesday':3, 
                'thursday':4, 
                'friday':5, 
                'saturday':6, 
                'sunday':7
            };
            var indexDay = associativeDays[selectedItem.val()];
            // FIXME : Show day in past or in future ?
            decay = indexDay-date.getDay();
            decay = decay*(3600*24*1000);
            date = new Date(date.getTime()+decay);
        } else {
            date = new Date();
        }
        $('#calendar').weekCalendar("gotoDate", date); 
        //$('#header_options_affichage_popup').dialog('close');
        $(window).resize(); 
        $('#calendar').weekCalendar('refresh');
    }
     
    // Send new configuration element
    if(column_name != undefined) {
        var post_array = {};
        post_array['column_name']  = base64_encode(column_name.toString());
        post_array['data_genre'] =  base64_encode(data_genre.toString());

        if(data_type == 'checkbox') {
            post_array['value'] = selectedItem.attr('checked')?'1':'0';
            post_array['value'] = base64_encode(post_array['value']);
        } else {
            post_array['value'] = base64_encode(selectedItem.val());
        }
        ajaxForce(WEBROOT+"/ajax_config", post_array, function(data) {
            $('.ajax-config-validator').show().delay(1500).fadeOut(500);
            if(selectedItem.attr('id') == 'save-sms-password' || selectedItem.attr('id') == 'save-sms-identifier' || selectedItem.attr('id') == 'version') {
                location.reload();
            }
        });
    }
    return true;
}

function save_general_config(selectedItem) {
    selectedItem.attr('data-genre', 'general_element');
    selectedItem.attr('value', $('#'+selectedItem.attr('data-column')).val());
    selectedItem.attr('name', selectedItem.attr('data-column'));
    
    ajax_config_element(selectedItem);
}

function export_data_to_excel(data_type){
    //window.location = WEBROOT+"/ajax_export/"+$('#'+data_type.attr('data-column')).val();
    if(data_type.parent().find('#ajax-cur-state').length > 0)
    {
        return false;
    }
    data_type.parent().append('<span id="ajax-cur-state"> Déjà exporté <span id="export-cur-count">0</span> elements...<img src="'+WEBROOT+'/images/general-ajax-loader-small.gif"></span>');

    var options = {
        begin:0, 
        count:100,
        action:'NEW'
    }; 
    
    var counter = data_type.parent().find('#export-cur-count');
   
    var while_loader = function(json_ret){
        counter.html(parseInt(counter.html()) + json_ret.count);
            
        options.begin = options.begin + options.count;
        options.action = 'CONTINUE';

        ajaxForce(WEBROOT+"/ajax_export/"+$('#'+data_type.attr('data-column')).val(), options, function(contunue_return) {
            
            var json_return = jQuery.parseJSON($.trim(contunue_return));
            if(parseInt(json_return.count)>0){
                check_function();
            }else{
                data_type.parent().find('#ajax-cur-state').html(counter.html()+" elements exportés, cliquez <a href='"+WEBROOT+json_return.target_file+"'>ici</a> pour telecharger le fichier.");
            }
        });
    };
    var check_function = function(){
        ajaxForce(WEBROOT+"/ajax_export/"+$('#'+data_type.attr('data-column')).val(), options, function(data) {

            var json_return = jQuery.parseJSON($.trim(data));
            if(parseInt(json_return.count)>0){
                while_loader(json_return);
            }else{
                data_type.parent().find('#ajax-cur-state').html(counter.html()+" elements exportés, cliquez <a href='"+WEBROOT+json_return.target_file+"'>ici</a> pour telecharger le fichier.");
            }
        });
    };
    
    check_function();
    return false;
} 
